package com.qyhl.school.school.reporter.sign;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.school.school.column.list.SchoolColumnListContract;
import com.qyhl.school.school.column.list.SchoolColumnListPresenter;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.InputDialog;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolListBean;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SCHOOL_REPORTER_SIGN_SCHOOL)
public class SchoolReportSignSchoolActivity extends BaseActivity implements SchoolColumnListContract.SchoolColumnListView {
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private SchoolColumnListPresenter mPresenter;

    private CommonAdapter<SchoolListBean> commonAdapter;

    private List<SchoolListBean> mDataList = new ArrayList<>();

    private int lastId = 0;

    private InputDialog.Builder builder;

    @Override
    protected int getContentView() {
        return R.layout.activity_school_reporter_sign_school;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new SchoolColumnListPresenter(this);

        mDataList = (List<SchoolListBean>) getIntent().getBundleExtra("bundle").getSerializable("list");

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setAdapter(commonAdapter = new CommonAdapter<SchoolListBean>(this, R.layout.item_practice_search_org, mDataList) {
            @Override
            protected void convert(ViewHolder holder, SchoolListBean schoolListBean, int position) {
                holder.setText(R.id.title, schoolListBean.getName());

                if (schoolListBean.isSelected()) {
                    holder.setImageResource(R.id.org_select, R.drawable.school_sex_on);
                } else {
                    holder.setImageResource(R.id.org_select, R.drawable.practice_search_org_off);
                }
            }
        });

        if (mDataList != null && mDataList.size() > 0) {
            loadMask.setStatus(LoadingLayout.Success);
            lastId = mDataList.get(mDataList.size() - 1).getId();
        } else {
            mPresenter.getSchoolList(0, lastId);
        }

    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                lastId = 0;
                mPresenter.getSchoolList(0, lastId);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                lastId = 0;
                mPresenter.getSchoolList(0, lastId);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getSchoolList(0, lastId);
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                for (int i = 0; i < mDataList.size(); i++) {
                    mDataList.get(i).setSelected(i == position);
                }
                commonAdapter.notifyDataSetChanged();

                boolean isSelected = false;
                for (int i = 0; i < mDataList.size(); i++) {
                    if (mDataList.get(i).isSelected()) {
                        isSelected = true;
                    }
                }

                if (isSelected) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) mDataList);
                    if (position == 0) {
                        builder = new InputDialog.Builder(SchoolReportSignSchoolActivity.this)
                                .setCancelable(false)
                                .setCanceledOnTouchOutside(false)
                                .setTitle("学校名称")
                                .setNegativeButton("取消", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                    }
                                }).setPositiveButtonWithOutDismiss("确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        String otherName = (String) v.getTag();
                                        if (StringUtils.isEmpty(otherName)) {
                                            showToast("学校名称不能为空！");
                                        } else {
                                            bundle.putString("name", otherName);
                                            intent.putExtras(bundle);
                                            setResult(RESULT_OK, intent);
                                            finish();
                                            hideKeyboard(v.getWindowToken());
                                            builder.dismiss();
                                        }
                                    }
                                });
                        builder.show();
                    } else {
                        intent.putExtras(bundle);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                } else {
                    showToast("请选择学校！");
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void setSchoolList(List<SchoolListBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            mDataList.addAll(beanList);
        } else {
            refresh.finishRefresh();
            mDataList.clear();
            mDataList.addAll(beanList);
            mDataList.add(0, new SchoolListBean("其他", 0));
        }
        lastId = beanList.get(beanList.size() - 1).getId();

        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(this)) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                showToast("暂无更多学校！");
            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @OnClick({R2.id.back_btn, R2.id.commit})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.commit) {
            if (mDataList != null && mDataList.size() > 0) {
                boolean isSelected = false;
                for (int i = 0; i < mDataList.size(); i++) {
                    if (mDataList.get(i).isSelected()) {
                        isSelected = true;
                    }
                }

                if (isSelected) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) mDataList);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    showToast("请选择学校！");
                }
            } else {
                showToast("暂无或未选择学校！");
            }
        }
    }
}
